package cn.iocoder.yudao.module.mybusiness.util;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.mybusiness.domain.Facility;
import cn.iocoder.yudao.module.mybusiness.domain.Job;
import cn.iocoder.yudao.module.mybusiness.domain.ProductionRecord;
import cn.iocoder.yudao.module.mybusiness.mapper.FacilityMapper;
import cn.iocoder.yudao.module.mybusiness.mapper.ModMapper;
import cn.iocoder.yudao.module.mybusiness.mapper.RecordMapper;
import cn.iocoder.yudao.module.mybusiness.mapper.TaskMapper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class TaskExecute implements Runnable{

    private Long fcfId;

    private List<Job> jobs;

    private TaskMapper taskMapper;

    private RecordMapper recordMapper;

    private Long taskId;

    private FacilityMapper facilityMapper;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String craft;

    public TaskExecute(Long fcfId, List<Job> workTimes, TaskMapper taskMapper, RecordMapper recordMapper,FacilityMapper facilityMapper, Long taskId,String craft) {
        this.fcfId = fcfId;
        this.jobs = workTimes;
        this.taskMapper = taskMapper;
        this.recordMapper = recordMapper;
        this.facilityMapper = facilityMapper;
        this.taskId = taskId;
        this.craft = craft;
    }

    @Override
    public void run() {
        jobs.forEach(job->{
            try {
                Facility facility = new Facility();
                facility.setId(fcfId);
                facility.setStatus(2);
                facilityMapper.updateById(facility);
                Thread.sleep(job.getProcessingTime()*1000);
                //修改任务数量
                taskMapper.upAccomplishNum(taskId);
                ProductionRecord record = new ProductionRecord();
                record.setTaskId(taskId);
                record.setFacId(fcfId);
                record.setModId(job.getModId());
                double randomNumber = Math.random();
                record.setResult(randomNumber<0.05?2:1);
                record.setCreateTime(format.format(new Date()));
                record.setModId(job.getModId());
                record.setCraft(craft);
                recordMapper.insert(record);
                facility.setStatus(1);
                facilityMapper.updateById(facility);
                System.out.println("=================设备编号:"+fcfId+"生产零件");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
